package com.yaDuo.common.base

import android.app.Activity
import android.content.res.Configuration
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.yaDuo.common.ui.DpiUtils

open class BaseActivity : AppCompatActivity() {

    companion object {
        const val TAG = "BaseActivity"
    }

    private var mFragmentProvider: ViewModelProvider? = null
    private var mActivityProvider: ViewModelProvider? = null
    private var mApplicationProvider: ViewModelProvider? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 分辨率适配工具初始化
        DpiUtils.applyDpi(this, this)
        // 支持使用矢量图
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
    }

    override fun onResume() {
        super.onResume()
        // 回到Activity时需要再调一次
        DpiUtils.applyDpi(this, this)
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        // Activity设置发生改变时也要重新设置
        DpiUtils.applyDpi(this, this)
    }

    protected fun <T : ViewModel> getFragmentScopeViewModel(modelClass: Class<T>): T {
        if (mFragmentProvider == null) {
            mFragmentProvider = ViewModelProvider(this)
        }
        return mFragmentProvider!![modelClass]
    }

    protected fun <T : ViewModel> getActivityScopeViewModel(modelClass: Class<T>): T {
        if (mActivityProvider == null) {
            mActivityProvider = ViewModelProvider(this)
        }
        return mActivityProvider!![modelClass]
    }

    protected fun <T : ViewModel> getApplicationScopeViewModel(modelClass: Class<T>): T {
        if (mApplicationProvider == null) {
            mApplicationProvider = ViewModelProvider(
                this.applicationContext as BaseApplication, getApplicationFactory(this)
            )
        }
        return mApplicationProvider!![modelClass]
    }

    private fun getApplicationFactory(activity: Activity): ViewModelProvider.Factory {
        val application = activity.application
        return ViewModelProvider.AndroidViewModelFactory.getInstance(application)
    }

    protected fun getContext(): Activity {
        return this
    }
}